const xlsx = require('node-xlsx'); // 读取xlsx文件模块
const fs = require('fs'); // 读取文件模块

// 导入常量
const {
  CONFIG_READ_PATH,
  FIELDS_READ_PATH,
  GENERATE_DIRNAME,
  GENERATE_COLUMNS_DIRNAME,
  GENERATE_FORM_DIRNAME,
  CHARACTER_ENCODING,
  DS_NAME,
  INTL_PREFIX,
  EXCEL_SHEET_NAME,
  QUERY_FIELD_NAME,
  QUERY_FIELD_CODE,
  FIELD_NAME,
  FIELD_CODE,
  ALIGN,
  TOOLTIP_INC_TYPE,
  TOOLTIP,
  DATE_TYPE,
  QUERY_CONDITION,
  NON_EDITABLE,
  TOOLTIP_INC_FIELD,
  EXCEL_CONFIG_ORDER,
} = require('./utils/constants/index');

// 导入方法
const {
  objectToString,
  arrayToString,
  underlineToHump,
  filterEmptyProps,
  createSpecialText,
  stringTrim,
  createFormItemText,
} = require('./utils/util');
const {
  createTransportText,
} = require('./utils/url');

// 存储最终DS文本
let DSText;
// 存储最终columns文本
let columnsText;
// 存储最终form文本
let formText;

// 定义生成DS方法
function ceateDS() {
  // 读取配置文件
  fs.readFile(CONFIG_READ_PATH, CHARACTER_ENCODING, function(err, data) {
    if(err) throw err;
    console.log(createSpecialText('-+- 读取DS配置文件成功！ -+-'));

    const {
      dsName = DS_NAME, // DS名称
      intlPrefix = INTL_PREFIX, // 多语言前缀
      readUrl, // read请求部分接口
      submitUrl, // submit请求部分接口
      destroyUrl, // destroy请求部分接口
      dsConfigObj = {}, // DS其它配置
    } = filterEmptyProps(JSON.parse(data) || {});
    const {
      paging = true, // 根据这个字段来判断生成columns(true)文件还是form(false)文件
    } = dsConfigObj;

    // 其它配置的字符串
    let _othercConfigText = objectToString(dsConfigObj);
    othercConfigText = `\n${_othercConfigText}\n`;

    // 读取表格配置 
    const sheetsArr = xlsx.parse(FIELDS_READ_PATH) || [];
    console.log(createSpecialText('-+- 读取表格配置文件成功！ -+-'));
    
    const fieldsConfig = sheetsArr.filter(sheet => sheet.name === EXCEL_SHEET_NAME)[0].data || [];
    // 实际字段配置数据
    const fieldsConfigArr = [...fieldsConfig];
    if(fieldsConfigArr.length) {
      // 删除表头(第一项)
      fieldsConfigArr.shift();
    }

    // 查询条件(queryFields)对象数组
    let queryFields = [];
    const queryFieldsArr = fieldsConfigArr.filter(field => field.includes(QUERY_CONDITION)) || [];
    if(queryFieldsArr.length) {
      queryFieldsArr.forEach(queryField => {
        if(queryField.length) {
          const { DESCRIBE_INDEX, FIELD_INDEX, DATA_TYPE_INDEX, LOOKUPCODE_INDEX } = EXCEL_CONFIG_ORDER || {};
          // 生成queryFields对象中的属性
          const name = underlineToHump(stringTrim(queryField[FIELD_INDEX]) || QUERY_FIELD_CODE);
          const lookupCode = stringTrim(queryField[LOOKUPCODE_INDEX]);
          const type = lookupCode ? null : stringTrim(queryField[DATA_TYPE_INDEX]) || DATE_TYPE;
          const label = `intl.get('${intlPrefix}.model.${name}').d('${(stringTrim(queryField[DESCRIBE_INDEX]) || QUERY_FIELD_NAME)}')`;
          // 生成queryFields
          const obj = filterEmptyProps({ name, lookupCode, type, label });
          queryFields.push(obj);
        }
      });
    }
    // 处理生成写入字符串
    let queryFieldsText = arrayToString(queryFields);
    queryFieldsText = `queryFields: [\n    ${queryFieldsText}\n  ],\n`;
    console.log(createSpecialText('-+- 生成queryFields属性成功！ -+-'));

    // fields对象数组
    let fields = [];
    const fieldsArr = [...fieldsConfigArr];
    if(fieldsArr.length) {
      fieldsArr.forEach(field => {
        if(field.length) {
          const { DESCRIBE_INDEX, FIELD_INDEX, DATA_TYPE_INDEX, LOOKUPCODE_INDEX } = EXCEL_CONFIG_ORDER || {};
          // 生成fields对象中的属性
          const name = underlineToHump(stringTrim(field[FIELD_INDEX]) || FIELD_CODE);
          const lookupCode = stringTrim(field[LOOKUPCODE_INDEX]);
          const type = lookupCode ? null : stringTrim(field[DATA_TYPE_INDEX]) || DATE_TYPE;
          const label = `intl.get('${intlPrefix}.model.${name}').d('${(stringTrim(field[DESCRIBE_INDEX]) || FIELD_NAME)}')`;
          // 生成fields
          const obj = filterEmptyProps({ name, lookupCode, type, label });
          fields.push(obj);
        }
      });
    }
    // 处理生成写入字符串
    let fieldsText = arrayToString(fields);
    fieldsText = `fields: [\n    ${fieldsText}\n  ],\n`;
    console.log(createSpecialText('-+- 生成fields属性成功！ -+-'));

    // transport
    const transportObj = filterEmptyProps({ readUrl, submitUrl, destroyUrl });
    let transportText = createTransportText(transportObj);
    console.log(createSpecialText('-+- 生成transport属性成功！ -+-'));

    const writeText = `${othercConfigText}  ${queryFieldsText}  ${fieldsText}  ${transportText}`;

    DSText = `const ${dsName}DS = () => ({${writeText}});`;
    // 生成最终DS文件
    if(DSText) {
      const startDsLogText = `-+- 开始生成${dsName}DS.js文件... -+-`;
      console.log(createSpecialText(startDsLogText));

      // 生成文件目录
      const writePath = GENERATE_DIRNAME + `${dsName}DS.js`;
      fs.writeFile(writePath, DSText, CHARACTER_ENCODING, function(err) {
        if(err) throw err;
        const finishDsLogText = `-+- ${dsName}DS.js文件生成成功! -+-`;
        console.log(createSpecialText(finishDsLogText));
        console.log(`${createSpecialText('文件目录:', '44', '37', '1m')}${createSpecialText(writePath, '40', '33')}`);

        // 清空文本
        DSText = null;
      });
    }

    // 生成其它配置文件
    if(paging) {
      console.log(createSpecialText('-+- 开始生成columnsjs文件... -+-'));
      console.log('--------------------------------------');

      let columns = [];
      const columnsArr = [...fieldsConfigArr];
      if(columnsArr.length) {
        columnsArr.forEach(column => {
          if(column.length) {
            const { FIELD_INDEX, DATA_TYPE_INDEX, EDIT_INDEX } = EXCEL_CONFIG_ORDER || {};
            // 生成column对象中的属性
            const name = underlineToHump(stringTrim(column[FIELD_INDEX]) || FIELD_CODE);
            const align = ALIGN;
            const type = stringTrim(column[DATA_TYPE_INDEX]) || DATE_TYPE;
            const editor = (stringTrim(column[EDIT_INDEX]) || NON_EDITABLE) !== NON_EDITABLE ? true : null;
            // 根据字段名是否包含(默认: ['remark', 'reason'])来决定是否添加"tooltip"
            const flag = (TOOLTIP_INC_FIELD || []).some(item => name.toLowerCase().includes(item)) || type === TOOLTIP_INC_TYPE;
            const tooltip = flag ? TOOLTIP : null;
            // 生成column
            const obj = filterEmptyProps({ name, align, editor, tooltip });
            columns.push(obj);
          }
        });
      }
      // 处理生成写入字符串
      let _columnsText = arrayToString(columns);
      _fieldsText = `return [\n    ${_columnsText}\n  ];\n`;

      // 生成columns文件
      columnsText = `get columns() {\n  ${_fieldsText}}`;
      // 生成最终columns文件
      if(columnsText) {
        // 生成文件目录
        const writePath = GENERATE_COLUMNS_DIRNAME;
        fs.writeFile(writePath, columnsText, CHARACTER_ENCODING, function(err) {
          if(err) throw err;
          console.log(createSpecialText('-+- columns.js文件生成成功! -+-'));
          console.log(`${createSpecialText('文件目录:', '44', '37', '1m')}${createSpecialText(writePath, '40', '33')}`);

          // 清空文本
          columnsText = null;
        });
      }
    }else {
      console.log(createSpecialText('-+- 开始生成form.js文件... -+-'));
      console.log('-----------------------------');

      formText = '';
      const formsArr = [...fieldsConfigArr];
      if(formsArr.length) {
        formsArr.forEach(form => {
          if(form.length) {
            const { FIELD_INDEX, DATA_TYPE_INDEX, LOOKUPCODE_INDEX, EDIT_INDEX } = EXCEL_CONFIG_ORDER || {};
            // 生成form中的属性
            const name = underlineToHump(stringTrim(form[FIELD_INDEX]) || FIELD_CODE);
            const lookupCode = stringTrim(form[LOOKUPCODE_INDEX]);
            const type = lookupCode ? 'select' : stringTrim(form[DATA_TYPE_INDEX]) || DATE_TYPE;
            const edit = stringTrim(form[EDIT_INDEX]) || NON_EDITABLE;

            // 生成from文本
            formText = createFormItemText(formText, type, name, edit);
          }
        });
      }
      // 生成最终form文件
      if(formText) {
        // 生成文件目录
        const writePath = GENERATE_FORM_DIRNAME;
        fs.writeFile(writePath, formText, CHARACTER_ENCODING, function(err) {
          if(err) throw err;
          console.log(createSpecialText('-+- form.js文件生成成功! -+-'));
          console.log(`${createSpecialText('文件目录:', '44', '37', '1m')}${createSpecialText(writePath, '40', '33')}`);

          // 清空文本
          formText = null;
        });
      }
    }
  });
}

// 开始生成
ceateDS();
